package net.magicidea;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class BookDAO {

	private static String TAG = BookDAO.class.getSimpleName();
	Context ctx;
	private static BookDAO instance;
	DBHelper helper;
	
	private BookDAO(Context ctx)
	{
		 this.ctx = ctx;
		 helper = DBHelper.getInstance(ctx);
	}
	
	public static BookDAO getInstance(Context ctx)
	{
		if(instance == null)
		{
			synchronized (DBHelper.class) {
				if(instance == null)
				{
					instance = new BookDAO(ctx);
				}
			}
		}
		
		return instance;
	}
	
	
	
	public void insert(String amount, String message)
	{
		SQLiteDatabase db = helper.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("BOOK_TIME", Calendar.getInstance().getTimeInMillis());
		values.put("AMOUNT", amount);
		values.put("MSG", message);
		
		long rowID = db.insert(DBHelper.BOOK_TABLE_NAME, null, values);
		db.close();
		
		Log.d(TAG, "insert db success with amount..." + amount);
		
		if(rowID == -1)
		{
			throw new RuntimeException("insert fail");
		}
	}
	
	
	
	public BookItem[] list(Date begin, Date end)
	{
		SQLiteDatabase db = helper.getReadableDatabase();
		
		String[] conditions = new String[2];
		conditions[0] = String.valueOf(begin.getTime());
		conditions[1] = String.valueOf(end.getTime());
		
		Cursor cursor = db.query(DBHelper.BOOK_TABLE_NAME, new String[]{"BOOK_TIME, AMOUNT, MSG"}, "BOOK_TIME BETWEEN ? AND ?", conditions, null, null, "BOOK_TIME");
		
		BookItem[] itemList = new BookItem[cursor.getCount()];
		int idx = 0;
		while(cursor.moveToNext())
		{
			 Date bookTime = new Date(cursor.getLong(0) );
			 int amount = cursor.getInt(1);
			 String message = cursor.getString(2);
			 
			 itemList[idx] = new BookItem(bookTime, amount, message);
			 idx++;
		}
		cursor.close();
		db.close();
		
		return itemList;
		
	}
}
